package com.xjt.excel.util;
/*
import it.sauronsoftware.jave.AudioAttributes;
import it.sauronsoftware.jave.Encoder;
import it.sauronsoftware.jave.EncodingAttributes;
import it.sauronsoftware.jave.MultimediaInfo;
import it.sauronsoftware.jave.MyFFMPEGLocator;
import it.sauronsoftware.jave.VideoAttributes;*/

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.util.*;
/*
import com.gaf.web.servlet.SystemConfig;
import com.gaf.web.util.DateUtil;
import com.gaf.wqsm.pub.action.SafeUtil;
import com.jxxc.util.docToJPG.JOD4DocToPDF;*/

/*******************************************************************************
 * 文件操作类
 * 
 * @author Administrator
 * 
 */
public class FileUtil {

	private static final Logger log = LoggerFactory.getLogger(FileUtil.class);


	public static File multipartFileToFile(MultipartFile file) throws Exception {

		File toFile = null;
		if (file.equals("") || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 向文件中追加内容
	 * 
	 * @param content
	 *            文件内容
	 * @param filePath
	 *            文件路径
	 * @param append
	 *            是否追加内容，true表示追加内容，false为否，不追加内容
	 */
	public static void writeFile(String content, String filePath, boolean append)
			throws Exception {
		// FileOutputStream out = null;
		RandomAccessFile out = null;
		FileLock flout = null;
		FileChannel fcout = null;
		try {
			if (content.length() <= 0) {
				if (!append) {
					File fil = new File(filePath);
					fil.delete();
					fil.createNewFile();
				}
				return;
			}
			File file = new File(filePath);
			file.mkdirs();
			if (!(file.exists())) {
				file.createNewFile();
			} else {
				if (!append) {// 追加内容，则
					file.delete();
					file.createNewFile();
				}
			}
			// 对该文件加锁
			out = new RandomAccessFile(file, "rw");
			fcout = out.getChannel();
			// 设置超时时长
			int timeOut = 60;
			Boolean getLock = false;
			while (timeOut > 0) {
				try {
					timeOut = timeOut - 1;
					flout = fcout.tryLock();
					getLock = true;
					break;
				} catch (Exception e) {
					log.error("有其他线程正在操作该文件，等待1秒!");
					Thread.sleep(1000);
				}
			}
			// out = new FileOutputStream(file, append);
			byte[] b = content.getBytes(StandardCharsets.UTF_8);
			if (getLock) {
				out.seek(out.length());// 向文件结尾追加内容
				out.write(b);
			}
			if (flout != null) {
				flout.release();
			}
			fcout.close();
			out.close();
			out = null;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			if (flout != null) {
				flout.release();
			}
			if (fcout != null) {
				fcout.close();
			}
			if (out != null) {
				out.close();
			}

		}
	}


	/**
	 * 向文件中追加内容
	 * 
	 * @param content
	 *            文件内容
	 * @param filePath
	 *            文件路径
	 * @param append
	 *            是否追加内容，true表示追加内容，false为否，不追加内容
	 */
	public static void writeFile(String content, String filePath,
			boolean append, int timeOut) throws Exception {
		// FileOutputStream out = null;
		RandomAccessFile out = null;
		FileLock flout = null;
		FileChannel fcout = null;
		String rootPath = null;//SystemConfig.getParamPath("fileUtilPath");
		try {
			File file = new File(rootPath, filePath);
			File pFile = file.getParentFile();
			pFile.mkdirs();
			if (!(file.exists())) {
				file.createNewFile();
			} else {
				if (!append) {// 追加内容，则
					file.delete();
					file.createNewFile();
				}
			}
			if (content.trim().length() <= 0) {
				return;
			}
			// 对该文件加锁
			out = new RandomAccessFile(file, "rw");
			fcout = out.getChannel();
			// 设置超时时长
			timeOut = (timeOut == 0 ? 1 : timeOut);
			Boolean getLock = false;
			while (timeOut > 0) {
				try {
					timeOut = timeOut - 1;
					flout = fcout.tryLock();
					getLock = true;
					break;
				} catch (Exception e) {
					log.error("有其他线程正在操作该文件，等待1秒!");
					Thread.sleep(1000);
				}
			}
			// out = new FileOutputStream(file, append);
			// byte[] b = content.getBytes("UTF-8");
			if (getLock) {
				out.seek(out.length());// 向文件结尾追加内容
				out.writeUTF(new String(content.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8));
			}
			if (flout != null) {
				flout.release();
			}
			fcout.close();
			out.close();
			out = null;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			if (flout != null) {
				flout.release();
			}
			if (fcout != null) {
				fcout.close();
			}
			if (out != null) {
				out.close();
			}

		}
	}


	/**
	 * 拷贝文件到指定目录
	 * 
	 * @param srcPath
	 *            源文件路径
	 * @param destPath
	 *            目标文件路径
	 * @return true:拷贝成功 false:拷贝失败
	 */
	public static boolean copyFile(String srcPath, String destPath)
			throws Exception {
		FileInputStream is = null;
		FileOutputStream os = null;
		try {
			File dest = new File(destPath);
			dest.mkdirs();
			dest.delete();
			File fl = new File(srcPath);
			int length = (int) fl.length();
			is = new FileInputStream(srcPath);
			os = new FileOutputStream(destPath);
			byte[] b = new byte[length];
			is.read(b);
			os.write(b);
			is.close();
			os.close();
			return true;
		} catch (Exception e) {
			if (null != is) {
				is.close();
			}
			if (null != os) {
				os.close();
			}
			return false;
		}
	}

	
	/**
	 * 将一个大文件切割成若干个小文件的
	 * 
	 * @param curfile
	 *            文本文件路径
	 * @return 返回文件内容
	 */
	public static void curFile(String curfile) {
		File f = new File(curfile);
		try {
			if (!f.exists())
				throw new Exception();
			FileReader cf = new FileReader(curfile);
			BufferedReader is = new BufferedReader(cf);
			StringBuffer filecontent = new StringBuffer();
			int i=0;
			int j=0;
			String str = is.readLine();
			while (str != null) {
				i++;
				filecontent.append(str);
				str = is.readLine();
				if (str != null)
					filecontent.append("\n");
				if(i%1000==0){
					filecontent.append("commit;\n");
				}
				if(i>100000){
					j++;
					String dfPath=f.getAbsolutePath().replace(".", "")+"/"+j+f.getName();				
					filecontent.append("commit;\n");
					writeFile(filecontent.toString().replace("`tb_family_members`", "tb_family_members"), dfPath, false);
					i=0;
					filecontent=null;
					filecontent=new StringBuffer();
					
				}
			}
			
			if(i>0 && i<=100000){
				j++;
				String dfPath=f.getAbsolutePath().replace(".", "")+"/"+j+f.getName();				
				filecontent.append("commit;\n");
				writeFile(filecontent.toString().replace("`tb_family_members`", "tb_family_members"), dfPath, false);
				filecontent=null;				
			}
			
			is.close();
			cf.close();
			return;
		} catch (Exception e) {
			System.err.println("不能读属性文件: " + curfile + " \n" + e.getMessage());
			return;
		}
	}
	

}
